package com.sam.lazyload;

/**
 * 双重检查延迟单例
 * 
 * @author Administrator
 * 
 */
public class DoubleCheckInstantce {

	private DoubleCheckInstantce() {

	}

	/** volatile:防止编译器对代码执行重新排序 **/
	private volatile static DoubleCheckInstantce instance = null;

	public static DoubleCheckInstantce getInstance() {
		if (instance == null) {
			/** 类对象锁 **/
			synchronized (DoubleCheckInstantce.class) {
				if (instance == null) {
					instance = new DoubleCheckInstantce();// instance为volatile，现在没问题了
				}

			}
		}
		return instance;
	}

	public static void main(String[] args) {

		for (int i = 0; i < 100; i++) {

			new Thread(new Runnable() {

				@Override
				public void run() {

					System.out.println(Thread.currentThread().getName()
							+ "获取实例："
							+ DoubleCheckInstantce.getInstance().toString());

				}
			}).start();
		}

		System.out.println(Thread.currentThread().getName() + "获取实例："
				+ DoubleCheckInstantce.getInstance().toString());

	}

}
